package server;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

public class Logger {
	private String subject;
	private BufferedWriter out;
	private String accessError;
	public Logger(String username, String rank, String org){
		subject = rank + " " + username + " from " + org+": ";

		accessError = "";
	}
	public void log(int command, String action, boolean accessOK, boolean packageOK){
		if(!packageOK)
			logToFile("Bad package was sent to server -_-");
		else if(!accessOK)
			logAccesError(command, action);
		else log(command, action);
	}
	
	private void logAccesError(int command, String file) {
		accessError = "ACCESS DENIED: ";
		log(command, file);
	}
	private  void log(int command, String file){
		String output = "Nothing";
		switch(command){
		   case Server.NEW:
			   output = subject + "created new file " + "\""+file+"\"";
			   	break;
		   case Server.SAVE: 
			   output = subject + "saved to file " + "\""+file+"\"";
			   	break;
		   case Server.DELETE: 
			   output = subject + "deleted file " + "\""+file+"\"";
			    break;
		   case Server.OPEN: 
			   output = subject + "opened file " + "\""+file+"\"";
			   break;
		   default: 
		}
		logToFile(output);
	}
	
	private void logToFile(String item){
		FileWriter fstream = null;
		try {
			fstream = new FileWriter("other/logg.txt",true);
		} catch (IOException e) {
			System.out.println("[DEBUG]: Failed to open logg.txt");
		}
		out = new BufferedWriter(fstream);
		
		try {
			out.write(dateStamp()+" "+accessError+item+"\n");
		} catch (IOException e) {
			System.out.println("[DEBUG]: Logger failed to log@logFile");
		}
		accessError = "";
		
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private String dateStamp(){
		String c = Calendar.getInstance().getTime().toString();
		return "["+c+"]";
	}
	
	
}
